package stackdemo;

import java.util.Stack;

public class Test {

    //栈的压入、弹出序列
    public boolean IsPopOrder (int[] pushV, int[] popV) {
        // write code here
        Stack<Integer> stack = new Stack<>();
        int j = 0;
        for (int i = 0; i < pushV.length; i++) {
            stack.push(pushV[i]);
            while (!stack.isEmpty() && stack.peek() == popV[j] && j < popV.length) {
                stack.pop();
                j++;
            }
        }
        return stack.isEmpty();
    }

    //括号匹配问题
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            // ch是左括号时入栈
            if (ch == '(' || ch == '{' || ch == '[') {
                stack.push(ch);
            } else {
                // ch是右括号时
                if (stack.isEmpty()) {
                    return false;
                }
                char peekCh = stack.peek();
                if (peekCh == '(' && ch == ')'
                        || peekCh == '{' && ch == '}'
                        || peekCh == '[' && ch == ']') {
                    stack.pop();
                } else {
                    return false;
                }
            }
        }
        // 字符串遍历完了，但栈不为空
        if (!stack.isEmpty()) {
            return false;
        }
        return true;
    }
}
